package com.huyun.web.concurrency.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Semaphore1 implements  Runnable {

    //只能5个线程同时访问
    final Semaphore semaphore = new Semaphore(5);
    @Override
    public void run() {
        try {
            //获取许可
            semaphore.acquire();
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName()+":done!");
            // 访问完后，释放
            semaphore.release();
            //availablePermits()指的是当前信号灯库中有多少个可以被使用
            System.out.println("-----------------" + semaphore.availablePermits());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        final Semaphore1 semaphore1=new Semaphore1();
//        Thread[] thread = new Thread[20];
//        for (int i=0 ; i<20 ; i++){
//            thread[i] = new Thread(semaphore1);
//        }
//        for (int i=0 ; i<10 ; i++){
//            thread[i].start();
//        }
        // 模拟20个 客户端
        ExecutorService exec = Executors.newFixedThreadPool(20);
        final Semaphore1 semaphore1=new Semaphore1();
        for(int i=0;i<20;i++){
            exec.submit(semaphore1);
        }
    }
}
